import time  # 新增time模块
import random  # 用于随机延时
from datetime import datetime

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def get_stock_info_crawler(symbol):
    """
    使用Selenium获取动态加载的股票信息
    :param symbol: 6位股票代码
    :return: 包含实时价格的字典
    """
    # 构建新浪财经URL（A股示例）
    url = build_sina_finance_url(symbol)

    if not url:
        print(f"无效的股票代码格式: {symbol}")
        return None

    # 打印请求开始实际按
    start_time = print_start_time(symbol, url)

    driver = None

    try:
        # 创建 driver
        driver = create_driver(driver)

        # 访问页面
        driver.get(url)

        # 显式等待价格加载（最长20秒）
        price_element = WebDriverWait(driver, 20).until(
            # 等待元素可见（包含display:none的情况）
            EC.presence_of_element_located((By.ID, "price"))
        )

        current_price = price_element.text

        # 显式等待市盈率元素加载（最长20秒）
        pe_ratio_element = WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.XPATH, "//th[contains(text(),'市盈率')]/following-sibling::td"))
        )

        pe_ratio_ttm = pe_ratio_element.text

        # 提取动态内容
        stock_name = driver.find_element(By.CSS_SELECTOR, "#stockName .c8_name").text

        # 记录响应信息
        end_time = datetime.now()
        duration = (end_time - start_time).total_seconds() * 1000  # 转换为毫秒
        print(
            f"[{end_time.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}] 请求完成 - 股票代码: {symbol}, 状态码: 200, 耗时: {round(duration)}ms")

        return {
            "股票名称": stock_name,
            "当前价格": current_price,
            "TTM": pe_ratio_ttm
        }

    except Exception as e:
        # 异常时记录失败信息
        end_time = datetime.now()
        duration = (end_time - start_time).total_seconds() * 1000
        print(
            f"[{end_time.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}] 请求失败 - 股票代码: {symbol}, 错误: {str(e)}, 耗时: {round(duration)}ms")
        return None
    finally:
        if driver:
            driver.quit()


def print_start_time(symbol, url):
    # 记录请求开始时间
    start_time = datetime.now()
    print(f"[{start_time.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}] 请求开始 - 股票代码: {symbol}, URL: {url}")

    # 随机延时 2-5 秒（更隐蔽的反爬策略）
    time.sleep(random.uniform(2, 5))
    return start_time


def create_driver(driver):
    # 配置WebDriver路径（需修改为你的实际路径）, chromedriver 下载地址，https://googlechromelabs.github.io/chrome-for-testing/
    driver_path = "D:\\DevTools\\chromedriver-win64\\chromedriver.exe"
    service = Service(driver_path)
    # 初始化浏览器（无头模式可选）
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")  # 无界面模式
    driver = webdriver.Chrome(service=service, options=options)
    return driver


def build_sina_finance_url(symbol):
    """
    根据股票代码构建新浪财经公司页面URL
    :param symbol: 6位股票代码（字符串或数字）
    :return: 完整的URL字符串 或 None（无效代码）
    """
    symbol = str(symbol).zfill(6)  # 确保6位长度
    prefix = symbol[:3]

    # 市场类型映射
    market_map = {
        'SH': ['600', '601', '603', '605', '688'],  # 沪市
        'SZ': ['000', '001', '002', '300', '301'],  # 深市
        'BJ': ['43', '83', '87', '88']  # 北交所
    }

    # 确定市场类型
    market = None
    for mkt, prefixes in market_map.items():
        if prefix in prefixes:
            market = mkt
            break

    if not market:
        return None  # 无效股票代码

    # 构建URL（新浪财经使用小写市场代码）
    return f"http://finance.sina.com.cn/realstock/company/{market.lower()}{symbol}/nc.shtml"


# 示例调用
if __name__ == "__main__":
    stock_info = get_stock_info_crawler("300896")
    print(stock_info)
